package cc.sunni.article.controller;

import cc.sunni.api.BaseController;
import cc.sunni.api.controller.article.CommentControllerApi;
import cc.sunni.api.utils.PageUtils;
import cc.sunni.article.service.CommentPortalService;
import cc.sunni.common.Constant;
import cc.sunni.common.utils.R;
import cc.sunni.pojo.bo.CommentReplyBO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashSet;
import java.util.Set;

@RestController
public class CommentController extends BaseController implements CommentControllerApi {
    @Autowired
    private CommentPortalService commentPortalService;

    @Override
    public R createArticle(@Validated CommentReplyBO commentReplyBO) {
        // 1. 根据留言用户的id查询他的昵称，用于存入到数据表进行字段的冗余处理，从而避免多表关联查询的性能影响
        String userId = commentReplyBO.getCommentUserId();
        // 2. 发起restTemplate调用用户服务，获得用户侧昵称
        Set<String> idSet = new HashSet<>();
        idSet.add(userId);
        String nickname = getBasicUserList(idSet).get(0).getNickname();
        String face = getBasicUserList(idSet).get(0).getFace();
        // 3. 保存用户评论的信息到数据库
        commentPortalService.createComment(commentReplyBO.getArticleId(), commentReplyBO.getFatherId(), commentReplyBO.getContent(), userId, nickname, face);
        return R.ok();
    }

    @Override
    public R commentCounts(String articleId) {
        Integer counts = getCountsFromRedis(Constant.REDIS_ARTICLE_COMMENT_COUNTS + ":" + articleId);
        return R.ok(counts);
    }

    @Override
    public R list(String articleId, Integer page, Integer pageSize) {
        PageUtils gridResult = commentPortalService.queryArticleComments(articleId, page, pageSize);
        return R.ok(gridResult);
    }

    @Override
    public R mng(String writerId, Integer page, Integer pageSize) {
        PageUtils gridResult = commentPortalService.queryWriterCommentsMng(writerId, page, pageSize);
        return R.ok(gridResult);
    }

    @Override
    public R delete(String writerId, String commentId) {
        commentPortalService.deleteComment(writerId, commentId);
        return R.ok();
    }
}
